package cvi.com.reader.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.List;

import butterknife.BindView;
import cvi.com.reader.R;
import cvi.com.reader.base.BaseActivity;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager2;
import cvi.com.reader.uploadrecord.ProgressListener;
import cvi.com.reader.uploadrecord.ProgressRequestBody;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/*
 * 上传文件 报java.net.SocketException: sendto failed: EPIPE (Broken pipe)，这是因为服务器限制了大小，服务器主动把socket关闭了
 */
public class MainActivity2 extends BaseActivity {

    @BindView(R.id.textView)
    TextView textView;
    // todo 这里需要根据自己的ip修改一下
    // private String url = "http://192.168.11.129/v1/admin_LqI4jb.php/ajax/recordUploadForPhone";
    private String url = "http://192.168.11.129/admin_LqI4jb.php/ajax/recordUploadForPhone";
    private List<String> fileNames;
    private String FileStr;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main2;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void extrasDoSome(Bundle extras) {

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    private void initListener() {
       /* textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        upImage();
                    }
                }).start();
            }
        });*/
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    protected void initView() {
        initUploadFile();
        initListener();
        File file = new File(FileStr); //生成文件
        //根据文件的后缀名，获得文件类型
        String fileType = getMimeType(file.getName());
        //把文件封装在RequestBody里
        RequestBody requestBody = RequestBody.create(MediaType.parse(fileType), file);

        ProgressRequestBody progressBody = new ProgressRequestBody(MediaType.parse(fileType), file, new ProgressListener() {
            @Override
            public void onProgress(long currentBytes, long contentLength, boolean done) {
                Log.e("chris", "currentBytes:" + currentBytes);
                Log.e("chris", "contentLength" + contentLength);
                Log.e("chris", (100 * currentBytes) / contentLength + " % done ");
                Log.e("chris", "done:" + done);
                Log.e("chris", "================================");
                //当前上传的进度值
            }
        });
        MultipartBody.Part part = MultipartBody.Part.createFormData("record", file.getName(), progressBody);

        NetWorkManager2.getInstance().getNetWorkApiService().sendData(83,83,83,  46, 1, 6,6,6,6,6,6, part).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(MainActivity2.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        Toast.makeText(MainActivity2.this, "点赞成功！", Toast.LENGTH_LONG).show();
                    }
                });
    }

    //初始化上传文件的数据
    private void initUploadFile() {
        FileStr = "/storage/emulated/0/TheReader/wav/20200811034955.wav";

    }

    private void upImage() {

     /*   // 1.创建 OkHttpClient
        OkHttpClient mOkHttpClent = new OkHttpClient();
        // 2.创建 RequestBody
        MultipartBody.Builder builder = new MultipartBody.Builder();
        File file = new File(FileStr); //生成文件
        //根据文件的后缀名，获得文件类型
        String fileType = getMimeType(file.getName());
        builder.addFormDataPart("score", 83 + "");
        builder.addFormDataPart("bgm_id", "");
        builder.addFormDataPart("user_id", "5");
        builder.addFormDataPart("material_id", "46");
        builder.addFormDataPart("is_released", "1");
        builder.addFormDataPart( //给Builder添加上传的文件
                "record",  //请求的名字，这个要和服务器预定？？
                file.getName(), //文件的文字，服务器端用来解析的
                RequestBody.create(MediaType.parse(fileType), file) //创建RequestBody，把上传的文件放入
        );

        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(new ProgressRequestBody(requestBody, new ProgressListener() {
                    @Override
                    public void onProgress(long currentBytes, long contentLength, boolean done) {
                        Log.e("chris", "currentBytes:" + currentBytes);
                        Log.e("chris", "contentLength" + contentLength);
                        Log.e("chris", (100 * currentBytes) / contentLength + " % done ");
                        Log.e("chris", "done:" + done);
                        Log.e("chris", "================================");
                        //当前上传的进度值
                        int progress = (int) ((100 * currentBytes) / contentLength);
                    }
                }))
                .build();

        // 4.发起请求
        Call call = mOkHttpClent.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                Log.e("chris", "onFailure: " + e);
                runOnUiThread(new Runnable() { // 子线程弹Toast
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity2.this, "失败" + e, Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("chris", "成功" + response);
                runOnUiThread(new Runnable() { // 子线程弹Toast
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity2.this, "成功", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });*/

    }


    /**
     * 获取文件MimeType
     *
     * @param filename 文件名
     * @return
     */
    private static String getMimeType(String filename) {
        FileNameMap filenameMap = URLConnection.getFileNameMap();
        String contentType = filenameMap.getContentTypeFor(filename);
        if (contentType == null) {
            contentType = "multipart/form-data"; //* exe,所有的可执行程序
        }
        return contentType;
    }


}
